// pages/admin/write/write.js
const app = getApp();
let time = require('../../../../utils/time.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    formats: {},
    readOnly: false,
    // 键盘高度，大于0时才显示
    keyboardHeight: 0,
    isIOS: false,
    // 封面
    imgList: "",
    imgfileID:"",
    // 文章内容
    blog_data:""
  },

  // ======文章封面上传start========
  ChooseImage() {
    let that = this;
    // 让用户选择一张图片
    wx.chooseImage({
      success: chooseResult => {
        // 时间戳
        var timestamp = Date.parse(new Date());
        // console.log("chooseResult：",chooseResult)
        // 将图片上传至云存储空间
        wx.showLoading({
          title: '上传中...',
        })
        wx.cloud.uploadFile({
          // 图片在云端的存储路径
          cloudPath: 'besidesApplets/blogfm/'+timestamp+'.png', 
          // 图片临时文件路径
          filePath: chooseResult.tempFilePaths[0], 
          success: res => {
            // console.log("图片存储成功：",res)
            // 返回文件 ID
            // console.log("返回文件 ID:",res.fileID)
            wx.cloud.getTempFileURL({
              fileList: [{
                fileID: res.fileID,
              }]
            }).then(res => {
              // get temp file URL
              // console.log(res)
              // console.log("获取临时链接：",res.fileList)
              console.log("临时链接：",res.fileList[0].tempFileURL)
              this.setData({
                imgList: res.fileList[0].tempFileURL
              })
            }).catch(error => {
              // handle error
            })
            // 隐藏
            wx.hideLoading()
            that.setData({
              imgfileID: res.fileID
            })
            // console.log("图片fileID是否赋值成功imgList：",that.data.imgList)
          },
          fail: console.error
        })
      }
    });
  },
  ViewImage(e) {
    console.log("显示：",e)
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  // 根据fileID删除图片
  DelImg(e) {
    let that = this
    wx.showModal({
      title: '召唤师',
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          console.log("点击了确定删除：",res)
          // this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          // that.ViewImage()
          wx.cloud.deleteFile({
            fileList: [that.data.imgfileID],
            success: res => {
              // handle success
              wx.showToast({
                title: '删除成功！',
              })
              console.log("删除成功：",res.fileList)
              that.setData({
                imgList: ""
              })
            },
            fail: console.error
          })
          
        }
      }
    })
  },
  // ======文章封面上传end========


  // =============富文本编辑器（文章内容）start=======
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },

  handleContentInput(e) {
    let that=this
    // console.log("editor输入事件：",e)
    // console.log("editor输入内容：",e.detail)
    console.log("editor输入HTML内容：",e.detail.html)
    const value = e.detail.html
    that.setData({
      blog_data: value
    })
    // console.log("文章内容是否赋值成功blog_data:",this.data.blog_data)
    //要将图片的头http://*.*.*.去掉/at/g
    // var reg = new RegExp(config.attachmenturl, "g")
    // this.data.content = value.replace(reg, '');
    // this.data.contentCount = value.length
    // $digest(this)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({skin: app.globalData.skin})

    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS})
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          data: {
            id: 'abcd',
            role: 'god'
          },
          width: '100%',
          success: function () {
            console.log('insert image success（图片插入成功！）')
          }
        })
      }
    })
  },
  // =============富文本编辑器（文章内容） end=======

  // 提交表单（发布）
  formSubmit(e) {
    wx.showLoading({
      title: '发布中...',
    })
    let that = this
    console.log("点击了提交：",e)
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    // 时间戳
    var timestamp = Date.parse(new Date());
    // console.log("时间戳转化为时间：",time.customFormatTime(timestamp,'Y-M-D'))
    let resultTag = e.detail.value.tag
    var tagArr = resultTag.split(",")

    let param={
      _id:timestamp,
      firstPicture: that.data.imgList,
      title: e.detail.value.blog_title,
      tag: tagArr,
      Likes: 0,
      Views: 1,
      time: time.customFormatTime(timestamp,'Y-M-D'),
      content: that.data.blog_data
    }

    // 调用云函数存入数据库
    wx.cloud.callFunction({
      name: "add",
      // 传递的参数
      data:{
        dbName: "test",
        param: param,
      }
    }).then( res => {
      console.log("插入数据云函数回调：",res)
      if(res.result){
        // 隐藏
        wx.hideLoading()
        wx.showToast({
          title: '发布成功！',
        })
      }else{
        // 隐藏
        wx.hideLoading()
        wx.showToast({
          title: '发布失败',
          icon: 'none'
        })
      }
      
    }).catch(error => {
      console.log("add云函数调用失败~");
      console.log(error)
      // 隐藏
      wx.hideLoading()
      wx.showToast({
        title: 'add云函数调用失败~',
        icon: 'none'
      })
    })

  },

  formReset(e) {
    console.log("重置：",e)
    console.log('form发生了reset事件，携带数据为：', e.detail.value)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})